package com.custom.common.filter;

import com.custom.common.helper.ThreadCache;
import com.custom.common.helper.WrappedHttpServletRequest;
import com.custom.common.util.RequestStreamUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @version: 1.0
 * @Author:
 * @Date: 2018-05-24 15:32
 */
@WebFilter(urlPatterns = "/*", filterName = "InterfaceFilter")
public class InterfaceFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(InterfaceFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

       // System.out.println(req.getParameter("a"));
       // System.out.println("request = [" + request + "], response = [" + response + "], chain = [" + chain + "]");
        try {
           WrappedHttpServletRequest wrappedHttpServletRequest = new WrappedHttpServletRequest(req);
            String params = wrappedHttpServletRequest.getRequestParams();;
            if ("POST".equals(req.getMethod().toUpperCase())) {
                 // 获取请求参数
               // ThreadCache.setPostRequestParams(params);
                logger.info("filer-post请求参数:[params={}]", params);
            } else {
                logger.info("非post请求");
            }
           // String ps = RequestStreamUtil.toString(req);

            ThreadCache.setPostRequestParams(params);
            chain.doFilter(request, response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public void destroy() {

    }
}